from app import db, login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class User(UserMixin, db.Model):
    __tablename__ = 'user'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    user_type = db.Column(db.String(20), nullable=False)  # farmer, researcher, government, enterprise
    
    USER_TYPES = {
        'admin': '系统管理员',
        'farmer': '农户',
        'researcher': '农业科研人员',
        'government': '农业部门工作人员',
        'enterprise': '农业企业管理人员'
    }
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def get_user_type_display(self):
        return self.USER_TYPES.get(self.user_type, '未知')

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id)) 